package com.yb.chapter1;

import java.util.Stack;

/**
 * 描述：编写一个类，用两个栈实现队列，
 * 要求：满足队列的 add  poll peek 操作
 * 思路： 栈两次翻转数据结构  == 队列
 *
 * @author yb
 * @date 2021/12/24 15:34
 */
public class QueueBaseStack {
    private Stack<Integer> inStack;
    private Stack<Integer> outStack;

    public QueueBaseStack(){
        inStack = new Stack<Integer>();
        outStack = new Stack<Integer>();
    }

    public boolean add(Integer data){
        return inStack.push(data) != null;
    }

    public Integer peek(){
        checkNull();
        //翻转栈，peek 之后再翻转回去
        while(!inStack.isEmpty()){
            outStack.push(inStack.pop());
        }
        final Integer peek = outStack.peek();
        while (!outStack.isEmpty()){
            inStack.push(outStack.pop());
        }
        return peek;
    }

    public Integer poll(){
        checkNull();
        //翻转栈，poll 之后再翻转回去
        while(!inStack.isEmpty()){
            outStack.push(inStack.pop());
        }
        final Integer pop = outStack.pop();
        while (!outStack.isEmpty()){
            inStack.push(outStack.pop());
        }
        return pop;
    }


    private void checkNull(){
        if(inStack.isEmpty()){
            throw new NullPointerException("队列空");
        }
    }


    public static void main(String[] args) {
        QueueBaseStack queue = new QueueBaseStack();
        queue.add(1);
        queue.add(2);
        System.out.println(queue.poll());
        queue.add(3);
        queue.add(4);
        System.out.println(queue.poll());
    }

}
